package com.bocai.dahuatech.ui.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bocai.dahuatech.Bean.BaseBean;
import com.bocai.dahuatech.Bean.CodeBean;
import com.bocai.dahuatech.Bean.IndividualBean;
import com.bocai.dahuatech.R;
import com.bocai.dahuatech.base.BaseActivity;
import com.bocai.dahuatech.event.MainEvent;
import com.bocai.dahuatech.utils.AESUtils;
import com.bocai.dahuatech.utils.DialogUtil;
import com.bocai.dahuatech.utils.MyConst;
import com.google.gson.Gson;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 个人会员注册
 */
public class RegistPersonalActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.btn_registtrue)
    Button btnRegist;
    @Bind(R.id.et_regist_name)
    EditText etName;
    @Bind(R.id.et_regist_password)
    EditText etPwd;
    @Bind(R.id.et_regist_password_true)
    EditText etPwdtrue;
    @Bind(R.id.et_regist_phone)
    EditText etPhone;
    @Bind(R.id.et_regist_code)
    EditText etCode;
    @Bind(R.id.et_regist_companyname)
    EditText etCompanyName;
    @Bind(R.id.et_regist_companyaddr)
    EditText etCompanyAddr;
    @Bind(R.id.ll_regist_companyaddr)
    LinearLayout llCompanyAddr;
    @Bind(R.id.btn_regist_getcode)
    Button btnGetCode;
    @Bind(R.id.tv_regist_companyaddr)
    TextView tvCompanyAddr;
    String []citys;
    private int delaytime;
    String what;
    boolean isPerson=true;
    IndividualBean bean=new IndividualBean();
    @Override
    protected int contentView() {
        return R.layout.activity_regist_personal;
    }

    @Override
    protected void initView()
    {
        ButterKnife.bind(this);
        what=getIntent().getStringExtra("what");
        if("person".equals(what))
        {
            isPerson=true;
            btnRegist.setText(R.string.identification);
            initToolbar(R.string.registperson);
        }else{
            isPerson=false;
            btnRegist.setText(R.string.next);
            initToolbar(R.string.registinfo);
            mToolbar.inflateMenu(R.menu.menu_next);
        }

        initEvent();

    }
    @Override
    protected void initEvent()
    {
        super.initEvent();
        btnRegist.setOnClickListener(this);
        llCompanyAddr.setOnClickListener(this);
        btnGetCode.setOnClickListener(this);
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                next();
                return false;
            }
        });
    }
    Observer<BaseBean> myMatchListBeanObserver=new Observer<BaseBean>()
    {

        @Override
        public void onCompleted()
        {

        }

        @Override
        public void onError(Throwable e)
        {
            hideLoading();
            showToast(R.string.neterror);
            Log.e("basebean", e.toString());
        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            hideLoading();
            Log.e("basebean",baseBean.getReturnInfo());
            if("1".equals(baseBean.getReturnNo()))
            {
                showToast(R.string.registpersonsuccese);
                finish();
            }else
            {
                showError(baseBean.getReturnInfo());
            }
        }
    };
    Observer<BaseBean> observer=new Observer<BaseBean>()
    {
        @Override
        public void onCompleted()
        {

        }

        @Override
        public void onError(Throwable e)
        {
            hideLoading();
            showToast(R.string.neterror);
            Log.e("error",e.toString());

        }

        @Override
        public void onNext(BaseBean baseBean)
        {
            hideLoading();
            if(baseBean.getReturnNo().equals("1"))
            {
                String result=AESUtils.decode(baseBean.getContent());
                if("true".equals(result))
                {
                    showToast(R.string.usernamealreadyuse);
                }else if("false".equals(result))
                {
                    if(etCode.getText().toString().equals(MyConst.code))
                    {

                        commitInfo(bean);
                    }else
                    {
                        showToast(R.string.codefalse);
                    }
                }
            }else
            {
                showToast(baseBean.getReturnInfo());
            }
        }
    };

    @Override
    public void onEventMainThread(MainEvent event)
    {
        super.onEventMainThread(event);
        if(event.msg.equals("citychoseover"))
        {
            tvCompanyAddr.setText(event.city);
            citys=event.city.split("-");
//            String cityId=event.cityId;
        }else  if("registisover".equals(event.msg))
        {
            finish();
        }

    }
    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            //获取验证码
            case R.id.btn_regist_getcode:
                getCode();
                break;
            case R.id.ll_regist_companyaddr:
                //省市区选择
                startActivity(new Intent(this,ProviceListActivity.class));
                break;

            case R.id.btn_registtrue:

                next();


                break;
        }
    }

    private void next() {
        if(TextUtils.isEmpty(etName.getText().toString()))
        {
            showToast(R.string.usernamenotnull);
        }
        else if(TextUtils.isEmpty(etPwd.getText().toString()))
        {
            showToast(R.string.psdnotnull);
        }
        else if(TextUtils.isEmpty(etPwdtrue.getText().toString()))
        {
            showToast(R.string.psdtruenotnull);
        }
        else if(TextUtils.isEmpty(etPhone.getText().toString()))
        {
            showToast(R.string.phonenotnull);
        }
        else if(etPhone.getText().toString().length()!=11)
        {
            showToast(R.string.phonefalse);
        }
        else if(TextUtils.isEmpty(etCode.getText().toString()))
        {
            showToast(R.string.codenotnull);
        }
        else if(TextUtils.isEmpty(etCompanyName.getText().toString()))
        {
            showToast(R.string.companynamenotnull);
        }
        else if(TextUtils.isEmpty(tvCompanyAddr.getText().toString()))
        {
            showToast(R.string.companyaddressnotnull);
        }
        else if(TextUtils.isEmpty(etCompanyAddr.getText().toString()))
        {
            showToast(R.string.addressnotnull);
        }
        else if(!etPwd.getText().toString().equals(etPwdtrue.getText().toString()))
        {
            showToast(R.string.psdfalse);
        }else
        {

            bean.setLoginName(etName.getText().toString());
            bean.setPassword(AESUtils.md5(etPwd.getText().toString()));
            bean.setPhone(etPhone.getText().toString());
            bean.setCompanyName(etCompanyName.getText().toString());
            bean.setProvince(citys[0]);
            bean.setCity(citys[1]);
            bean.setArea(citys[2]);
            bean.setAddress(etCompanyAddr.getText().toString());
            //判断用户名是否有效
            getTestApi().userNameExit(etName.getText().toString())
                    .compose(this.<BaseBean>bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        }
    }

    /**
     * 获取验证码
     */
    private void getCode()
    {
        if(TextUtils.isEmpty(etPhone.getText().toString()))
        {
            showToast(R.string.phonenotnull);
        }
        else if(etPhone.getText().toString().length()!=11)
        {
            showToast(R.string.phonefalse);
        }else{

            getTestApi().getCode(etPhone.getText().toString())
                    .compose(this.<BaseBean>bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<BaseBean>()
                    {
                        @Override
                        public void onCompleted()
                        {

                        }

                        @Override
                        public void onError(Throwable e)
                        {
                            showToast(R.string.neterror);
                        }

                        @Override
                        public void onNext(BaseBean baseBean)
                        {
                            if(baseBean.getReturnNo().equals("1"))
                            {
                                String result=AESUtils.decode(baseBean.getContent());
                                result=start+result+end;
                                Log.e("result", result);
                                CodeBean bean=new Gson().fromJson(result,CodeBean.class);
                                MyConst.code=bean.getContent()+"";
                                Toast.makeText(RegistPersonalActivity.this, R.string.codeisout, Toast.LENGTH_SHORT).show();
                                delaytime = 60;
                                btnGetCode.setClickable(false);
                                new Thread(new ThreadShow()).start();
                            }else
                            {
                                showToast(R.string.codegetfalse);
                            }
                        }
                    });
        }
    }
    // 线程类
    class ThreadShow implements Runnable
    {
        @Override
        public void run()
        {
            while (delaytime > 0)
            {
                try
                {
                    Thread.sleep(1000);
                    delaytime--;
                    Message msg = new Message();
                    msg.what = 88;
                    handler.sendMessage(msg);
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    Handler handler=new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            switch (msg.what)
            {
                case 88:
                    btnGetCode.setText(delaytime + "s");
                    if (delaytime == 0)
                    {
                        btnGetCode.setClickable(true);
                        btnGetCode.setText(R.string.send);
                    }
                    break;
            }
        }
    };

    /**
     * 如果是个人注册，提交个人注册信息
     * 如果是分销商注册，将第一步注册的信息传递到注册的第二个界面
     * @param bean
     */
    private void commitInfo(final IndividualBean bean)
    {
        if(isPerson)
        {
            registpersonInfo(bean);
        }else
        {
            getTestApi().checkCompanyName(bean.getCompanyName(),bean.getPhone())
                    .compose(this.<BaseBean>bindToLifecycle())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<BaseBean>()
                    {
                        @Override
                        public void onCompleted()
                        {

                        }

                        @Override
                        public void onError(Throwable e)
                        {
                            showToast(R.string.neterror);
                        }

                        @Override
                        public void onNext(BaseBean baseBean)
                        {
                            if (baseBean.getReturnNo().equals("1"))
                            {
                                String result=AESUtils.decode(baseBean.getContent());
                                if("1".equals(result.toLowerCase()))
                                {
                                    Intent intent = new Intent(RegistPersonalActivity.this, RegistDistributorSecendActivity.class);
                                    intent.putExtra("register", bean);
                                    intent.putExtra("what", "regist");
                                    startActivity(intent);
                                }else if ("2".equals(result.toLowerCase()))
                                {
                                    DialogUtil.dialogForTwoButton(RegistPersonalActivity.this, R.string.alreadysubmittologin, R.string.dismiss, R.string.agreen, new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v)
                                        {
                                            registpersonInfo(bean);
                                            DialogUtil.dismissTowDialog();
                                        }
                                    });
                                }else if ("3".equals(result.toLowerCase())){
                                    showToast(R.string.phonerepeat);
                                }

                            }else
                            {
                                showToast(baseBean.getReturnInfo());
                            }
                        }
                    });

        }
    }

    private void registpersonInfo(IndividualBean bean)
    {
        showLoading();
        getTestApi().register(bean.getLoginName(), bean.getPassword(),bean.getPhone(),bean.getCompanyName(), bean.getProvince(), bean.getCity(), bean.getArea(), bean.getAddress())
                .compose(this.<BaseBean>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(myMatchListBeanObserver);
    }
}
